// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129

const db = uniCloud.database()
const wallpaperDB = db.collection("wallpaper")
module.exports = {
	_before: function() { // 通用预处理器

	},
	async addFile(event) {
		try {
			const {
				openid,
				userId,
				filePath
			} = event

			function getRandomArbitrary(min, max) {
				return Math.random() * (max - min) + min;
			}

			function getRandomNumber(min, max) {
				return Math.floor(getRandomArbitrary(min, max + 1));
			}

			let addInfo = await wallpaperDB.add({
				openid,
				path: filePath,
				showCount: getRandomNumber(450, 680),
				userId,
				createTime: new Date().getTime()
			})
			return {
				code: 200,
				addInfo: addInfo,
				msg: '添加成功'
			}
		} catch (e) {
			//TODO handle the exception
			return {
				code: 500,
				msg: e
			}
		}
	},
	// 获取发送到照片广场的数据
	async getAsyncPhoto(event) {
		try {

			let limit = 100; // 每次查询的数量
			let offset = 0; // 偏移量	
			const whereInfo = {}
			let resultCount = await wallpaperDB.where(whereInfo).count(); // 总数量		
			let userList = []
			do {
				let resultData = await wallpaperDB.where(whereInfo).skip(offset).limit(limit)
					.get();
				userList = userList.concat(resultData.data); // 将查询到的数据添加到列表中	 
				offset += limit; // 更新偏移量
			} while (offset < resultCount.total);
			return {
				code: 200,
				msg: '操作成功',
				data: userList
			}
		} catch (e) {
			return {
				code: 500,
				data: e
			}
		}
	},
	// 记录操作
	async showWallpaper(event) {
		try {

			let {
				data
			} = await wallpaperDB.where({
				_id: event.imgId
			}).get()
			const updateData = {
				...data[0],
				showCount: data[0].showCount + 1
			}
			delete updateData._id
			let updateRes = await wallpaperDB.doc(event.imgId)
				.update(updateData)

			return {
				code: 200,
				msg: '操作成功',
			}
		} catch (e) {
			return {
				code: 500,
				data: e
			}
		}
	},
	// 批量上传图片并新增图片记录
	async batchUpload(event) {
		try {
			const {
				imageList = [],
				databaseCode='wallpaper'
			} = event
			const wallpaperDB = db.collection(databaseCode)
			let addInfo = await wallpaperDB.add(imageList)
			return {
				code: 200,
				addInfo: addInfo,
				msg: '添加成功'
			}


		} catch (e) {
			return {
				code: 500,
				addInfo: e,
				msg: '添加失败'
			}
			//TODO handle the exception
		}
	},

}